import axios from "./axios/axios";
import { isJSON, _deleteUndefined, _successDataHandle, _addDefaultParams, _consoleResult } from "./util";
import config from './config';
import { server_url } from './env';

const instance = axios.create({
  baseURL: server_url,
  timeout: 50000,
  data: {},
  headers: {
    "Content-type": "application/x-www-form-urlencoded",
    "token": wx.getStorageSync('token')
  }
})

//请求拦截
instance.interceptors.request.use(
  config => {
    config.startTime = +new Date()
    let data = _addDefaultParams(config.data)
    config.headers = {...config.headers, token: data.token }
    config.data = data
    // 将参数中为undefined的属性置''
    config = JSON.parse(JSON.stringify(_deleteUndefined(config)));
    return config
  },
  err => {
    console.error(err)
    return Promise.reject(err)
  }
)

//响应拦截
instance.interceptors.response.use(
  res => {
    if(res.statusCode === 200){
      // 输出返回结果和请求地址和参数
      _consoleResult(res);
      let server_data = res.data;
      // 判断是不是下载文件
      if(config.requestType === 'download'){
        return res;
      }
      // 判断服务器返回数据是不是【json字符串】
      if(isJSON(server_data)){
        server_data = JSON.parse(server_data)
      }
      // 成功返回的处理
      server_data = _successDataHandle(server_data, instance)
      return server_data;
    }
    return Promise.reject(res)
  },
  err => {
    console.warn(err)
    return Promise.reject(err)
  }
)
// 将config地址配置为axios对象的方法，方便直接访问
for(let key in config){
  instance[key.replace("Url", "")] = function(opts = {}){
    return instance.post(config[key], opts)
  }
} 

module.exports = instance;